<script lang="ts" setup>
import {onMounted, ref} from "vue";
import {useResourceStore} from "../../store/ResourceStore.ts";
import type {ThirdPartyEmoteCategory, ThirdPartyEmoteGroup} from "../../types/Emote.ts";
import type {BbsCodeBody, EmoteGroup} from "../../network/types/Resources.ts";


const resourceStore = useResourceStore();

const emoteGroups = ref<EmoteGroup[]>()
const thirdPartyEmoteGroups = ref<ThirdPartyEmoteGroup[]>()
const blockedNames = ref<string[]>()
const switchMap = ref<{ [key: string]: boolean }>({})

onMounted(async () => {
  blockedNames.value = resourceStore.blockedNames()

  resourceStore.bbsCode().then((res: BbsCodeBody) => {
    emoteGroups.value = res.emoteGroups

    emoteGroups.value?.forEach(i => {
      switchMap.value[i.name] = !blockedNames.value!!.includes(i.name)
    })

  })

  resourceStore.thirdPartyEmoteCategory().then((res: ThirdPartyEmoteCategory[]) => {
    thirdPartyEmoteGroups.value = res.flatMap(i => i.groups)

    thirdPartyEmoteGroups.value?.forEach(i => {
      switchMap.value[i.name] = !blockedNames.value!!.includes(i.name)
    })
  })
})

const onSwitchChange = (name: string, value: boolean) => {
  console.log(name, value)
  const arr = blockedNames.value ? [...blockedNames.value!!] : []
  if (value) {
    blockedNames.value = resourceStore.blockedNames(arr.filter(i => i !== name))
  } else {
    blockedNames.value = resourceStore.blockedNames([...arr, name])
  }
}


</script>

<template>
  <div style="text-align: start">
    <h2>官方</h2>
    <div v-if="emoteGroups">
      <div v-for="(group, index) in emoteGroups" :key="index" class="clickable emote-group-div">
        <el-image :src="group.emotes[0].url.replace('https://img4.nga.178.com','/static/res')"
                  class="emote-group-cover"
                  loading="lazy"
        />
        <br>
        <el-switch v-model="switchMap[group.name]" :active-text="group.name" @change="onSwitchChange(group.name,$event)"/>
      </div>
    </div>
    <h2>第三方</h2>
    <div v-if="thirdPartyEmoteGroups">
      <div v-for="(group, index) in thirdPartyEmoteGroups" :key="index" class="clickable emote-group-div">
        <el-image :src="group.data[0].img.replace('./','/static/attach/attachments/')"
                  class="emote-group-cover"
                  loading="lazy"
        />
        <br>
        <el-switch v-model="switchMap[group.name]" :active-text="group.name" @change="onSwitchChange(group.name,$event)"/>
      </div>
    </div>
  </div>

</template>

<style scoped>
.emote-group-cover {
  width: 100px;
}

.emote-group-div {
  display: inline-block;
  margin-right: 10px;
}
</style>